<template>
  <div class="xiaozhi-container">
    <!-- 导航栏标题 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      @click-left="$router.back()"
      fixed
    >
      <template slot="title">
        <span>小智同学</span> &nbsp;
        <van-icon name="friends" dot />
      </template>
    </van-nav-bar>

    <div class="chat_content" ref="mychartRef"></div>

    <!-- 底部聊天输入框 -->
    <div class="bottom_input">
      <van-field
        v-model="inputVal"
        center
        clearable
        placeholder="请输入内容"
        @keyup.enter="sendFn"
      >
        <template #button>
          <van-button size="mini" round type="info" @click="sendFn"
            >发送</van-button
          >
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
// import io from 'socket.io-client'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      inputVal: '',
      scoket: null,
      charArr: []
    }
  },
  computed: {
    ...mapState(['user'])
  },
  mounted () {
    // const token = this.user.token
    // this.scoket = io('http://ttapi.research.itcast.cn')
    // this.scoket.on('message', msg => {
    //   this.scoket.emit('message', { token: token })
    //   this.charArr.push({
    //     content: msg,
    //     isRoot: true
    //   })
    // })
  },
  watch: {
    charArr () {
      this.$nextTick(() => {
        this.$refs.mychartRef.scrollTop = this.$refs.mychartRef.scrollHeight
      })
    }
  },
  methods: {
    sendFn () {
      if (this.inputVal.trim().length === 0) return
      console.log(this.inputVal)

      // this.scoket.emit('message', {
      //   msg: this.inputVal,
      //   timestamp: Date.now()
      // })
      this.charArr.push({
        content: this.inputVal,
        isRoot: false
      })
      this.inputVal = ''
    }
  }
}
</script>

<style lang="less" scoped>
.chat_content {
  margin-top: 80px;
  width: 100%;
  height: 100%;
  border: 1px solid gray;
}
.bottom_input {
  position: fixed;
  right: 0;
  left: 0;
  bottom: 0;
  height: 100px;
  width: 100%;
  border: 1px soild gray;
}
</style>
